<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索框 -->
        <el-row>
          <!-- 搜索 -->
          <el-col :span="12">
            <el-form :inline="true" :model="formData">
              <el-form-item label="学科名称">
                <el-input v-model="formData.subject"> </el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="clearSubject">清除</el-button>
                <el-button type="primary" @click="searchSubjects">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button
              icon="el-icon-edit"
              type="success"
              @click="
                () => {
                  this.isShowDialog = true
                }
              "
              >新增学科</el-button
            >
          </el-col>
        </el-row>
        <!-- 消息提示 -->
        <el-alert :title="`数据一共${total} 条`" type="info" show-icon :closable="false">
        </el-alert>
        <!-- 表格 -->
        <el-table :data="subjectList">
          <el-table-column label="序号" width="50" type="index" :index="indexMethod">
          </el-table-column>
          <el-table-column prop="subjectName" label="学科名称"> </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期" width="160">
            <template #default="{ row }">
              {{ dateFormat(row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="isFrontDisplay"
            label="前台是否显示"
            width="80"
            :formatter="statusFormat"
          >
          </el-table-column>
          <el-table-column prop="twoLevelDirectory" label="二级目录" width="80"> </el-table-column>
          <el-table-column prop="tags" label="标签" width="80"> </el-table-column>
          <el-table-column prop="totals" label="题目数量" width="80"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="{ row }">
              <el-button type="text" @click="toDirectorys(row)">学科分类</el-button>
              <el-button type="text" @click="toTags(row)">学科标签</el-button>
              <el-button type="text" @click="editSubject(row)">修改</el-button>
              <el-button type="text" @click="delSubject(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="prev, pager, next,sizes, jumper"
          :total="total"
          style="display: flex; justify-content: end; margin-top: 15px"
        >
        </el-pagination>
      </el-card>
      <!-- 弹框 -->
      <el-dialog
        :title="title"
        :visible="isShowDialog"
        @close="closeDialog"
        width="35%"
        :close-on-click-modal="false"
      >
        <el-form :model="dialogForm" :rules="rules" ref="addForm">
          <el-form-item label="学科名称" prop="subjectName">
            <el-input v-model="dialogForm.subjectName" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="是否显示">
            <el-switch
              v-model="dialogForm.isFrontDisplay"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" style="display: flex; justify-content: end">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="addSubject">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list, add, remove, update, detail } from '@/api/hmmm/subjects.js'
import dayjs from 'dayjs'
export default {
  data () {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      formData: { subject: '' },
      subjectList: [], // 学科列表
      isShowDialog: false, // 控制弹框显示隐藏
      dialogForm: {
        subjectName: '',
        isFrontDisplay: 1 // 控制弹框里的显示开关
      },
      rules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title () {
      return this.dialogForm.id ? '编辑学科' : '添加学科'
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 关闭弹框
    closeDialog () {
      this.isShowDialog = false
      this.$refs.addForm.resetFields()
      this.dialogForm = {
        subjectName: '',
        isFrontDisplay: 1 // 控制弹框里的显示开关
      }
    },

    // 渲染页面
    async getList () {
      const { data } = await list({
        page: this.page,
        pagesize: this.pageSize,
        subjectName: this.formData.subject
      })
      // console.log(data)
      this.subjectList = data.items
      this.total = data.counts
    },

    // 改变每页容量
    handleSizeChange (pageSize) {
      // console.log(pageSize)
      this.pageSize = pageSize
      this.getList()
    },

    // 改变当前页
    handleCurrentChange (page) {
      this.page = page
      this.getList()
    },

    // 改变序号
    indexMethod (index) {
      // console.log(index)
      return (this.page - 1) * this.pageSize + index + 1
    },

    // 格式化时间
    dateFormat (date) {
      return dayjs(date).format('YYYY-MM-DD hh:mm:ss')
    },

    // 格式化是否显示
    statusFormat (row, column, cellValue, index) {
      return cellValue ? '是' : '否'
    },

    // 清除筛选内容
    clearSubject () {
      this.formData.subject = ''
      this.getList()
    },

    // 查询学科
    async searchSubjects () {
      this.page = 1
      await this.getList()

      // if (this.formData.subject) {
      //   const res = this.subjectList.filter(item =>
      //     item.subjectName.includes(this.formData.subject)
      //   )
      //   this.subjectList = res
      //   this.total = res.length
      //   this.page = 1
      // } else {
      //   this.page = 1
      //   this.getList()
      // }
    },

    // 添加学科,编辑学科
    addSubject () {
      // 显示弹框
      this.isShowDialog = true
      // 整体校验
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        if (this.dialogForm.id) {
          // 编辑学科
          await update(this.dialogForm)
          this.$message.success('修改学科成功')
          // console.log(res)
        } else {
          await add(this.dialogForm)
          this.$message.success('新增学科成功')
        }

        // 关闭弹框
        this.closeDialog()

        // 渲染页面
        this.page = 1
        this.getList()
      })
    },

    // 删除学科
    delSubject (row) {
      this.$confirm('此操作将永久删除该学科，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          // console.log(data)
          // console.log(123);
          const num = this.total - (this.page - 1) * this.pageSize
          if (num === 1 && this.page !== 1) {
            this.page--
          }
          // 重新渲染列表
          this.getList()
          this.$message.success('删除学科成功')
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 修改学科，数据回显
    async editSubject (row) {
      this.isShowDialog = true
      // 数据回显
      const { data } = await detail(row)
      this.dialogForm = data
    },

    // 跳转到学科分类
    toDirectorys (row) {
      // console.log(row)
      this.$router.push(`/subjects/directorys?id=${row.id}&name=${row.subjectName}`)
    },

    // 跳转到学科标签
    toTags (row) {
      this.$router.push(`/subjects/tags?id=${row.id}&name=${row.subjectName}`)
    }
  }
}
</script>

<style scoped></style>
